from flask import Blueprint, jsonify, request
from flask_login import current_user, login_user, logout_user
from CreateUser.models import User, db
from CreateUser.forms import RegisterForm, LoginForm
from CreateUser.extensions import bcrypt

bp = Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/register', methods=['POST'])
def register():
    user_data = request.get_json()
    print(user_data)
    form = RegisterForm(data=user_data)
    if form.validate():
        user = User(username=user_data['username'], password=user_data['password'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'status': 'success'})
    return jsonify({'status': 'error', 'message': form.errors}), 400


@bp.route('/login', methods=['POST'])
def login():
    user_data = request.get_json()
    form = LoginForm(data=user_data)
    if form.validate():
        user = form.get_user()
        login_user(user, remember=form.remember.data)
        return jsonify({'status': 'success', 'user': user.to_json()})
    return jsonify({'status': 'error', 'message': form.errors}), 403


@bp.route('/login/alterPassword', methods=['POST'])
def alter():
    formdata = request.json
    if len(formdata['password'])<8:
        return jsonify({
            'code': -1,
            'msg': '密码长度至少为8个'
        })
    if formdata['password'] != formdata['password2']:
        return jsonify({
            'code': -1,
            'msg': '两个密码不一样'
        })
    user = User.query.filter(User.username == formdata['username']).first()
    if user == None:
        return jsonify({
            'code': -1,
            'msg': '用户不存在'
        })

    if not bcrypt.check_password_hash(user.password.encode(), formdata['old_password']):
        return jsonify({
            'code': -1,
            'msg': '原密码错误'
        })
    user.password = bcrypt.generate_password_hash(formdata['password'])
    db.session.add(user)
    db.session.commit()
    return jsonify({
        'code': 0,
        'msg': '修改成功'
    })


@bp.route('/session')
def get_session():
    if not current_user.is_authenticated:
        return jsonify({'status': 'error'}), 401
    return jsonify({'status': 'success', 'user': current_user.to_json()})


@bp.route('/logout')
def logout():
    logout_user()
    return jsonify({'status': 'success'})
